package com.example.miscontactos;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.example.miscontactos.Entidades.EnviarMensajeHandler;
import com.example.miscontactos.Entidades.GetMensajesWebHandler;
import com.example.miscontactos.Entidades.MensajesWebsEntity;
import com.example.miscontactos.Entidades.NombreAccion;
import com.example.miscontactos.Entidades.RegistrarUserWebHandler;

import BaseDeDatos.AccesoABaseDeDatos;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.Toast;

public class Utilities extends Activity 
{

	private static String ESTA_ONLINE = "estadoConexion";
	
	static Intent RealizarLlamada(String nro) 
	{
		String url = "tel:" + nro;
		Intent intent;
		if(nro != ""){
			intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));	
		}
		else
		{
			intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
		}
		
		return intent;
	}
	
	static Intent enviarSMS(String nro) 
	{
		Uri uri = Uri.parse("smsto:" + nro);
		Intent intent;
		if(nro != ""){
			intent = new Intent(Intent.ACTION_SENDTO, uri);	
		}
		else
		{
			intent = new Intent(Intent.ACTION_SENDTO, uri);
		}				
		return intent;
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_utilities);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        getMenuInflater().inflate(R.menu.activity_utilities, menu);
        return true;
    }
    
    public static Boolean crearUsuarioWeb(byte[] xml, Context con)
    {
    	Boolean logueadoExitosamente = false;
    	try
    	{
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://192.168.0.26:8080/MessageSender/Sender");
			BasicHttpEntity ent = new BasicHttpEntity();
			ent.setContentType("application/xml");
			ByteArrayInputStream in = new ByteArrayInputStream(xml);
			ent.setContent(in);
			post.setEntity(ent);						
			HttpResponse responsePost= client.execute(post);
			HttpEntity resEntity= responsePost.getEntity();
			
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser(); 
			RegistrarUserWebHandler handler= new RegistrarUserWebHandler();
									
			if(resEntity != null)
			{
				String res= EntityUtils.toString(resEntity);
				parser.parse(new ByteArrayInputStream(res.getBytes()), handler);
				// Guardo la preferencia
				/*String error = handler.getUserName().getError();
				if(error.equals(""))
				{*/
					SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(con);
				    SharedPreferences.Editor editor = app_preferences.edit();
				    editor.putBoolean(ESTA_ONLINE, true);
				    editor.commit();		
				    logueadoExitosamente = true;
				/*}
				else
				{
					Toast.makeText(con, error, Toast.LENGTH_LONG).show();
				}*/
			}
			else
			{
				Toast.makeText(con, handler.getUserName().getError(), Toast.LENGTH_LONG).show();
			}
    	}
    	catch (Exception e) 
    	{
			e.printStackTrace();
			Toast.makeText(con, "Error!!!", Toast.LENGTH_LONG).show();
		}
    	return logueadoExitosamente;
    }
    
    public static void pullMensajesWebs(byte[] xml, Context con)
    {
    	try
    	{
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://192.168.0.26:8080/MessageSender/Sender");
			BasicHttpEntity ent = new BasicHttpEntity();
			ent.setContentType("application/xml");
			ByteArrayInputStream in = new ByteArrayInputStream(xml);
			ent.setContent(in);
			post.setEntity(ent);						
			HttpResponse responsePost= client.execute(post);
			HttpEntity resEntity= responsePost.getEntity();
			
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser(); 
			GetMensajesWebHandler handler= new GetMensajesWebHandler();
									
			if(resEntity != null)
			{
				String res= EntityUtils.toString(resEntity);
				parser.parse(new ByteArrayInputStream(res.getBytes()), handler);
				List<MensajesWebsEntity> mensajesNuevos = handler.getNuevosMensajes();			
				for (MensajesWebsEntity mensajesWebsEntity : mensajesNuevos) 
				{
					if (mensajesWebsEntity != null)
						AccesoABaseDeDatos.registrarAccionHistorialConFecha(con, "", "", "", mensajesWebsEntity.from, NombreAccion.MensajeWeb,mensajesWebsEntity.mensaje, mensajesWebsEntity.fecha);
				}
			}
			else
			{
				Toast.makeText(con, handler.getErrorMessage(), Toast.LENGTH_LONG).show();
			}
    	}
    	catch (Exception e) 
    	{
			e.printStackTrace();
			Toast.makeText(con, "Error!!!", Toast.LENGTH_LONG).show();
		}
    }
    
    public static Boolean enviarMensaje(byte[] xml, Context con)
    {
    	Boolean enviadoExitosamente = false;
    	EnviarMensajeHandler handler = new EnviarMensajeHandler();;
    	try
    	{
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://192.168.0.26:8080/MessageSender/Sender");
			BasicHttpEntity ent = new BasicHttpEntity();
			ent.setContentType("application/xml");
			ByteArrayInputStream in = new ByteArrayInputStream(xml);
			ent.setContent(in);
			post.setEntity(ent);						
			HttpResponse responsePost= client.execute(post);
			HttpEntity resEntity= responsePost.getEntity();
			
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser(); 
									
			if(resEntity != null)
			{
				String res= EntityUtils.toString(resEntity);
				parser.parse(new ByteArrayInputStream(res.getBytes()), handler);
				MensajesWebsEntity mensajeEnviado = handler.getMensajeWebResponse();
				if(mensajeEnviado.error == null)
					enviadoExitosamente = true;
			}
			else
			{
				Toast.makeText(con, handler.getMensajeWebResponse().error, Toast.LENGTH_LONG).show();
			}
    	}
    	catch (Exception e) 
    	{
			e.printStackTrace();			
			Toast.makeText(con, handler.getMensajeWebResponse().error, Toast.LENGTH_LONG).show();//"Error!!!", Toast.LENGTH_LONG).show();
		}
    	return enviadoExitosamente;
    }
    
}
